package com.zhiche.lisa.tms.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.oms.dto.ShipmentOrderDTO;
import com.zhiche.lisa.oms.dto.TransportationTypeDTO;
import com.zhiche.lisa.oms.vo.LocationTypeVo;
import com.zhiche.lisa.tms.dao.mapper.ShipOrderItemMapper;
import com.zhiche.lisa.tms.dao.model.ShipOrderItem;
import com.zhiche.lisa.tms.dao.model.ShipTask;
import com.zhiche.lisa.tms.dao.model.Shipment;
import com.zhiche.lisa.tms.dao.model.TmsExplogLine;
import com.zhiche.lisa.tms.dto.ReceiptDTO;
import com.zhiche.lisa.tms.service.*;
import com.zhiche.lisa.tms.vo.ShipmentListInfoVo;
import com.zhiche.lisa.util.MdmUtil;
import com.zhiche.lisa.util.RandomUtil;
import com.zhiche.lisa.util.UaaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p>
 * 运单货物明细 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-06-18
 */
@Service
public class ShipOrderItemServiceImpl extends ServiceImpl<ShipOrderItemMapper, ShipOrderItem> implements IShipOrderItemService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShipOrderItemServiceImpl.class);

    @Autowired
    private IShipmentService shipmentService;
    @Autowired
    private IShipTaskService shipTaskService;
    @Autowired
    private ShipOrderServiceImpl shipOrderService;
    @Autowired
    private TmsExplogLineService explogLineService;
    @Autowired
    private ShipmentServiceImpl shipmentServiceImpl;

    @Autowired
    private UaaUtil uaaUtil;
    @Autowired
    private MdmUtil mdmUtil;

    @Value("${lisa.lspm.isUnlcnFleetDriverUrl}")
    private String isUnlcnFleetDriverUrl;
    @Value("${lisa.lspm.getFleetListByMobileUrl}")
    private String getFleetListByMobileUrl;

    @Value("${integration.url}")
    private String integrationUrl;

    @Value("${integration.getPriceAndMilesUrl}")
    private String getPriceAndMilesUrl;
    @Value("${erp.cancelShipUrl}")
    private String cancelShipUrl;

    //连接超时时间
    @Value("${integration.socketTimeout}")
    private int socketTimeout;

    @Value("${lisa.wms.toBmsShipDateURL}")
    private String toBmsShipDateURL;
    @Override
    public ShipOrderItem getShipOrderItemById(Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new BaseException(-1, "运单货物明细ID，不能为空！");
        }
        return this.selectById(id);
    }

    /**
     * 根据来源唯一键查询运单货物明细
     *
     * @param itemSourceKey
     */
    @Override
    public ShipOrderItem queryShipOrderItem(String itemSourceKey) {
        ShipOrderItem cn = null;
        Wrapper<ShipOrderItem> ew = new EntityWrapper<>();
        if (itemSourceKey != null) {
            ew.eq("item_source_key", itemSourceKey);
            cn = this.selectOne(ew);
        }
        return cn;
    }

    @Override
    public Map<String, Object> queryPurchasePriceOtm(Long id) {

        if (ObjectUtils.isEmpty(id)) {
            throw new BaseException("参数id不能为空");
        }
        ShipOrderItem shipOrderItem = baseMapper.selectByIdNotenant(id);
        if (Objects.isNull(shipOrderItem)) {
            throw new BaseException("未查询到对应运单货物明细");
        }
        if (StringUtils.isBlank(shipOrderItem.getItemSourceKey())) {
            throw new BaseException("对应订单号为空");
        }
        Map<String, String> params = new HashMap<>();
        params.put("orderno", shipOrderItem.getItemSourceKey());
        String result = null;
        try {
            LOGGER.info("queryPurchasePriceOtm url:{},param:{}", integrationUrl + getPriceAndMilesUrl, JSONObject.toJSONString(params));
            result = HttpClientUtil.postJson(integrationUrl + getPriceAndMilesUrl, null, JSONObject.toJSONString(params), socketTimeout);
            LOGGER.info("queryPurchasePriceOtm url:{},result:{}", integrationUrl + getPriceAndMilesUrl, result);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSON.parseObject(result);
                Integer code = jsonObject.getInteger("code");
                JSONObject data = jsonObject.getJSONObject("data");
                if (code != null && code == 0 && data != null) {
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("id", id);
                    resultMap.put("price", data.get("price"));
                    resultMap.put("miles", data.get("miles"));
                    return resultMap;
                } else {
                    throw new BaseException(jsonObject.getString("message"));
                }
            } else {
                throw new BaseException("queryPurchasePriceOtm 未响应结果");
            }
        } catch (Exception e) {
            LOGGER.error("queryPurchasePriceOtm 连接OTM获取支付标准价超时异常 url:{},error:{}", integrationUrl + getPriceAndMilesUrl, e);
            throw new BaseException("queryPurchasePriceOtm 连接OTM获取支付标准价超时异常");
        }
    }

    @Override
    public List<ShipOrderItem> selectListNotenant(EntityWrapper<ShipOrderItem> itemEW) {
        return baseMapper.selectListNotenant(itemEW);
    }

    @Override
    public List<Map<String, Object>> getShipOrderItemByShipCode(String code) {

        return baseMapper.selectShipOrderItemByShipCode(code);
    }

    @Override
    public void updateByshipmentId(String orderReleaseId, String shipTime) {
        ShipOrderItem shipOrderItem = new ShipOrderItem();
        Wrapper<ShipOrderItem> ew=new EntityWrapper<>();
        Timestamp timestamp = new Timestamp(Long.valueOf(shipTime));
        shipOrderItem.setWmsShipTime(timestamp);
        ew.eq("item_source_key",orderReleaseId);
        baseMapper.update(shipOrderItem,ew);
    }

    @Override
    public List<ShipOrderItem> selectByShipmentId(String shipmentId) {
        return baseMapper.selectByShipmentId(shipmentId);
    }

    @Override
    public void selectWmsNotShipped() {
        Page<ShipOrderItem> page=new Page<>();
        page.setSize(200);
        int current=1;
        while (true){
            page.setCurrent(current++);
            List<String> shipOrderItems = baseMapper.selectWmsNotShippedNotenant(page);
            if (CollectionUtils.isEmpty(shipOrderItems)){
                return;
            }
            Map<String,Object> params=new HashMap<>();
            params.put("releaseGids",shipOrderItems);
            String result = HttpClientUtil.postJsoneRturnError(toBmsShipDateURL, null, JSONObject.toJSONString(params), socketTimeout);
            LOGGER.info("selectWmsNotShipped 同步wms发运时间 url:{},参数:{},result:{}", toBmsShipDateURL ,JSONObject.toJSONString(params),result);
        }
    }

    @Override
    public String cancelShipTime(Map<String,Object> map) {
        if (StringUtils.isEmpty(map.get("shipmentGid").toString())){
            throw new BaseException("指令号不能为空");
        }
        if (StringUtils.isEmpty(map.get("releaseGid").toString())){
            throw new BaseException("运单号不能为空");
        }
        if (StringUtils.isEmpty(map.get("vin").toString())){
            throw new BaseException("车架号不能为空");
        }

        EntityWrapper<ShipOrderItem> ew = new EntityWrapper<>();
        ew.eq("issue_item_id",map.get("vin").toString()).eq("item_source_key",map.get("releaseGid").toString());
        List<ShipOrderItem> shipOrderItems = baseMapper.selectList(ew);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(shipOrderItems)){
            throw new BaseException("该运单不存在");
        }
        ShipOrderItem shipOrderItem = shipOrderItems.get(0);

        EntityWrapper<ShipTask> shipTaskEntityWrapper=new EntityWrapper<>();
        shipTaskEntityWrapper.eq("ship_order_code",shipOrderItem.getShipOrderCode());
        List<ShipTask> shipTasks = shipTaskService.selectList(shipTaskEntityWrapper);
        ShipTask shipTask=new ShipTask();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(shipOrderItems)){
            shipTask = shipTasks.get(0);
        }
        if (shipTask.getGmtFinish()!=null){
            throw new BaseException("该运单已运抵,不能取消发运");
        }
        baseMapper.updateShipTime(ew);
        //根据指令号查询司机信息
        EntityWrapper<Shipment> shipmentEntityWrapper = new EntityWrapper<>();
        shipmentEntityWrapper.eq("ship_source_key", map.get("shipmentGid").toString());
        Shipment shipment = shipmentService.selectOne(shipmentEntityWrapper);

        //取消发运推送ERP
       String resToken = uaaUtil.getTenantToken("tech-" + shipment.getTenantId());
       if (shipment != null){
        if (StringUtils.isNotBlank(shipment.getDriverId())) {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            LOGGER.info("判断司机是否是中联自有 获取token:{}", resToken);
            headNamePairs.add(new BasicNameValuePair("Authorization", resToken));
            String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), headNamePairs, null, 60000);
            LOGGER.info("判断司机是否是中联自有车队返回结果 url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                String paramJson = JSONObject.toJSONString(map);
                TmsExplogLine explogLine = new TmsExplogLine();
                explogLine.setExportType("BS_CANCEL");
                explogLine.setExportKey(shipment.getShipSourceKey());
                explogLine.setTargetSys("ERP");
                explogLine.setInterfaceUrl(cancelShipUrl);
                explogLine.setDataContent(paramJson);
                explogLine.setGmtCreate(new Date());
                explogLine.setRemarks("自有车队取消发运推送ERP");
                try {
                    LOGGER.info("自有车队取消发运推送ERP url:{},param:{}", cancelShipUrl, paramJson);
                    String postJson = HttpClientUtil.postJson(cancelShipUrl, null, paramJson, 60000);
                    LOGGER.info("自有车队取消发运推送ERP 结果:{}", postJson);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                    explogLine.setExportResponse(postJson);
                } catch (Exception e) {
                    LOGGER.error("自有车队取消发运推送ERP 超时异常:url:{},params:{}", cancelShipUrl, paramJson);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                }
                explogLineService.insert(explogLine);
            }
        }
       }

        //取消发运推送bms
        shipOrderService.deletePricePurchase(resToken,shipTask,shipment,shipOrderItem);
        return "tms"+RandomUtil.game(6);
    }

    @Override
    public Page<ReceiptDTO> getReceiptList(Page<ReceiptDTO> page,String token) {
        Page<ReceiptDTO> pageVo = new Page<>();

        Map<String, Object> condition = page.getCondition();

        EntityWrapper<ShipOrderItem> ew=this.getEntityWrapper(condition,token);


        List<ReceiptDTO> ReceiptDTOs = baseMapper.getReceiptListNotenant(page, ew);

        if (!CollectionUtils.isEmpty(ReceiptDTOs)){
            for (ReceiptDTO receiptDTO : ReceiptDTOs) {
                if (StringUtils.isEmpty(receiptDTO.getAbnormalPodReason())){
                    receiptDTO.setStatus("0");
                }else {
                    receiptDTO.setStatus("1");
                }
            }
        }
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(ReceiptDTOs);
        return pageVo;
    }

    private EntityWrapper<ShipOrderItem> getEntityWrapper(Map<String, Object> condition,String token) {
        EntityWrapper<ShipOrderItem> ew = new EntityWrapper<>();
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数为空！");
        }
        // 获取登陆者信息
        JwtAccountVO account = AccountUtil.getAccountInfoFromSecurityContext();
        //EntityWrapper<Shipment> ew = new EntityWrapper<>();
        // 不是中联管理账号
        if(!"1".equals(account.getTenantId())){
            Object fleetIdStrings = condition.get("fleetId");
            if (Objects.isNull(fleetIdStrings) || org.springframework.util.StringUtils.isEmpty(fleetIdStrings.toString())) {
                String mobile = (String)condition.get("mobile");
                if(null == mobile || "".equals(mobile)){throw new BaseException("您还不是车队管理员！");}
                // 对接lspm拿取承运商车队信息
                fleetIdStrings = getLspFleet(account.getTenantId(),token);
                if(null == fleetIdStrings || "".equals(fleetIdStrings)){throw new BaseException("您还不是车队管理员！");}
            }
            List<String> fleetIds = Arrays.asList(fleetIdStrings.toString().split(","));
            ew.in("fleetId", fleetIds);
        }

        if (condition != null && !condition.isEmpty()) {

            if (null != condition.get("createTimeStart") && !org.springframework.util.StringUtils.isEmpty(condition.get("createTimeStart"))) {
                ew.ge("createTime", condition.get("createTimeStart"));
            }
            if (null != condition.get("createTimeEnd") && !org.springframework.util.StringUtils.isEmpty(condition.get("createTimeEnd"))) {
                ew.le("createTime", condition.get("createTimeEnd"));
            }
            if (null != condition.get("fleetName") && !org.springframework.util.StringUtils.isEmpty(condition.get("fleetName"))) {
                String[] fleetNameList = condition.get("fleetName").toString().split(",");
                ew.in("fleetName", fleetNameList);
            }
            if (null != condition.get("vin") && !org.springframework.util.StringUtils.isEmpty(condition.get("vin"))) {
                String[] vins = condition.get("vin").toString().trim().replace(" ", "").split(",|;|\n");
                ew.in("vin", vins);
            }
            if (null != condition.get("cusWaybillNo") && !org.springframework.util.StringUtils.isEmpty(condition.get("cusWaybillNo"))) {
                ew.eq("cusWaybillNo", condition.get("cusWaybillNo").toString());
            }
            if (null != condition.get("shipmentGid") && !org.springframework.util.StringUtils.isEmpty(condition.get("shipmentGid"))) {
                ew.eq("shipmentGid", condition.get("shipmentGid").toString());
            }
            if (null != condition.get("driverPhone") && !org.springframework.util.StringUtils.isEmpty(condition.get("driverPhone"))) {
                ew.eq("driverPhone", condition.get("driverPhone").toString());
            }
            if (null != condition.get("driverName") && !org.springframework.util.StringUtils.isEmpty(condition.get("driverName"))) {
                ew.eq("driverName", condition.get("driverName").toString());
            }
            if (null != condition.get("ciamsId") && !org.springframework.util.StringUtils.isEmpty(condition.get("ciamsId"))) {
                ew.eq("ciamsId", condition.get("ciamsId").toString());
            }
            if (null != condition.get("transportationId") && !org.springframework.util.StringUtils.isEmpty(condition.get("transportationId"))) {
                ew.eq("transportationId", condition.get("transportationId").toString());
            }
            if (null != condition.get("status") && !org.springframework.util.StringUtils.isEmpty(condition.get("status"))) {
                if ("1".equals(condition.get("status"))) {
                    ew.isNotNull("createTime");
                }
                if ("0".equals(condition.get("status"))) {
                    ew.isNull("createTime");
                }
            }
            if (null != condition.get("lspName") && !org.springframework.util.StringUtils.isEmpty(condition.get("lspName"))) {
                String[] lspNameList = condition.get("lspName").toString().split(",");
                ew.in("lspName", lspNameList);
            }

            if (null != condition.get("orderNo") && !org.springframework.util.StringUtils.isEmpty(condition.get("orderNo"))) {
                String[] orderNos = condition.get("orderNo").toString().trim().replace(" ", "").split(",|;|\n");
                ew.in("orderNo",orderNos );
            }
        }
        ew.groupBy("id");
        ew.orderBy("createTime",false);
        return ew;
    }


    public Object getLspFleet(String tenantId,String token) {
        Object fleetIdStrings;
        List<NameValuePair> headNamePairs = org.assertj.core.util.Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", token));
        List<Map<String,Object>> fleetResults = null;
        try {
            LOGGER.info("getShipmentListVoByFleetId info url:{},params:{} ", getFleetListByMobileUrl, tenantId);
            String fleetResult = HttpClientUtil.postJson(getFleetListByMobileUrl,headNamePairs, tenantId, socketTimeout);
            LOGGER.info("getShipmentListVoByFleetId result {} ", fleetResult);
            if(null == fleetResult || "".equals(fleetResult)){
                throw new BaseException("获取承运商车队信息错误，请稍后在试！");
            }
            RestfulResponse<List<Map<String, Object>>> response = JSONObject.parseObject(fleetResult, new TypeReference<RestfulResponse<List<Map<String, Object>>>>() {
            });
            if(null != response && null != response.getData()){
                fleetResults = response.getData();
            }
        } catch (Exception e) {
            LOGGER.error("getShipmentListVoByFleetId url:{},params:{} 连接超时:{}", getFleetListByMobileUrl, e);
            throw new BaseException(e.getMessage());
        }

        if(org.apache.commons.collections4.CollectionUtils.isEmpty(fleetResults)){
            throw new BaseException(-1,"您还没有车队！");
        }
        StringBuffer sb = new StringBuffer();
        for(Map<String,Object> map : fleetResults){
            sb.append(map.get("id") + ",");
        }
        fleetIdStrings = sb.substring(0, sb.length() - 1);
        return fleetIdStrings;
    }

    @Override
    public void receiptStatus(Map<String, String> map) {
        EntityWrapper<ShipOrderItem> ew = new EntityWrapper<>();
        ShipOrderItem shipOrderItem = new ShipOrderItem();
        if (StringUtils.isEmpty(map.get("orderGid"))){
          throw  new BaseException("订单号不能为空");
        }
        if (StringUtils.isEmpty(map.get("podStatus"))){
            throw  new BaseException("回单状态不能为空");
        }
        ew.eq("order_no",map.get("orderGid"));
        shipOrderItem.setReceiptStatus(map.get("podStatus"));
        baseMapper.update(shipOrderItem,ew);
    }

    @Override
    public List<ReceiptDTO> exportReceiptList(Map<String, Object> map,String token) {
        EntityWrapper<ShipOrderItem> ew = this.getEntityWrapper(map,token);
        List<ReceiptDTO> ReceiptDTOs = baseMapper.exportReceiptListNotenant(ew);
        return ReceiptDTOs;
    }

    @Override
    public ShipOrderItem getShipOrderItemByOrderNo(String orderNo,String itemSourceKey) {
        return baseMapper.getShipOrderItemByOrderNo(orderNo, itemSourceKey);
    }

    @Override
    public List<ShipOrderItem> getListNotenant(EntityWrapper<ShipOrderItem> shipOrderItemWrapper) {
        return baseMapper.getListNotenant(shipOrderItemWrapper);
    }


}
